package temp;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;

public class CentralServer {

	private ServerSocket welcomeSocket;
	private Socket connectionSocket;
	private Hashtable<String,NewFormat> files;

	public CentralServer(int serverPort) {

		try {
			welcomeSocket = new ServerSocket(serverPort);
			files = new Hashtable<String, NewFormat>();
			loadFiles();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	private void loadFiles() {
		try {
			System.out.println("loading files...");
			String fileName = "wave1.wav";
			File soundFile = new File(fileName);
			AudioInputStream audioStream = AudioSystem.getAudioInputStream(soundFile);
			NewFormat format = new NewFormat(audioStream.getFormat());
			files.put(fileName,format);
			System.out.println("file - " + fileName + " loaded." );
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	public void run(){
		while(true) 
		{
			try {
				System.out.println("waiting for connections...");
				connectionSocket = welcomeSocket.accept();      
				Thread s = new Thread(new MediaServer(connectionSocket,files));
				s.start();
				System.out.println("Accept connection - client port = :" + connectionSocket.getPort() );
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		CentralServer server = new CentralServer(Constants.CENTRAL_SEVER_TCP_PORT);
		server.run();
	}
}
